package com.ynet.middleground.riskmanage.model;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.riskmanage.bean.*;
import com.ynet.middleground.riskmanage.common.SystemConstant;
import com.ynet.middleground.riskmanage.dao.ColdChainDynamicPledgeMapper;
import com.ynet.middleground.riskmanage.dao.ColdChainStaticPledgeMapper;
import com.ynet.middleground.riskmanage.dao.DgPledgeStaticMapper;
import com.ynet.middleground.riskmanage.dto.PledgeOrderDTO;
import com.ynet.middleground.riskmanage.entity.ColdchainPledgeStatic;
import com.ynet.middleground.riskmanage.entity.DgPledgeStatic;
import com.ynet.middleground.riskmanage.entity.DynamicStaticResult;
import com.ynet.middleground.riskmanage.external.ErrorCodeEnum;
import com.ynet.middleground.riskmanage.external.MainBusinessConfig;
import com.ynet.middleground.riskmanage.external.codechain.ColdChainApiHelper;
import com.ynet.middleground.riskmanage.external.codechain.ColdChainUriEnum;
import com.ynet.middleground.riskmanage.external.port.PortApiHelper;
import com.ynet.middleground.riskmanage.external.port.PortUriEnum;
import com.ynet.middleground.riskmanage.mq.producer.PledgeProducer;
import com.ynet.middleground.riskmanage.utils.BeanUtil;

/**
 * @ClassName PledgeOrReliefPledgeOrderModel
 * @Description 冷链及大港-质押监管与解除质押监管（静态/动态/换货）
 * @Author zhangyongbin
 * @Date 2020/8/19 17:11
 * @Version 1.0
 */
@Component
public class PledgeOrReliefPledgeOrderModel {

    /**
     * 冷链渠道标识
     */
    private static final String CHANNEL_TYEP_COLDCHAIN = "0";

    /**
     * 大港渠道标识
     */
    private static final String CHANNEL_TYEP_PORT = "1";

    /**
     * 大港分配给金控的组织机构 id
     */
    private static final String PORT_ORANG_ID = "1";

    // /**
    // * 冷链分配给金控的账户 id
    // */
    // private static final String COLD_CHAIN_ACCOUNT_ID = "111";

    @Autowired
    ColdChainApiHelper coldChainApiHelper;

    @Autowired
    PortApiHelper portApiHelper;

    @Autowired
    ColdChainStaticPledgeMapper coldChainStaticPledgeMapper;

    @Autowired
    ColdChainDynamicPledgeMapper coldChainDynamicPledgeMapper;

    @Autowired
    DgPledgeStaticMapper dgPledgeStaticMapper;

    @Autowired
    PledgeProducer pledgeProducer;

    @Autowired
    Mapper mapper;

    @Autowired
    MainBusinessConfig mainBusinessConfig;

    /**
     * @Description 质押监管与解除质押监管（静态）
     * @Author zhangyongbin
     * @Date 2020/8/18 11:24
     * @Param [req] 请求信息
     * @return com.ynet.core.common.ServiceResult
     **/
    @Transactional(rollbackFor = Exception.class)
    public PledgeOrderDTO staticPledgeOrRelief(StaticPledgeOrReliefPledgeReq req) {
        if (CHANNEL_TYEP_COLDCHAIN.equals(req.getChanType())) {
            if (StringUtils.isEmpty(req.getTaskId())) {
                throw new BusinessException(ErrorCodeEnum.ECRM0002.getMsg(), ErrorCodeEnum.ECRM0002.getCode());
            }
            return coldChainStatic(req);
        } else if (CHANNEL_TYEP_PORT.equals(req.getChanType())) {
            // if (StringUtils.isEmpty(req.getShipNo())) {
            // throw new BusinessException(ErrorCodeEnum.ECRM0004.getMsg(), ErrorCodeEnum.ECRM0004.getCode());
            // }
            if (StringUtils.isEmpty(req.getSellNo())) {
                throw new BusinessException(ErrorCodeEnum.ECRM0005.getMsg(), ErrorCodeEnum.ECRM0005.getCode());
            }
            if ("JCZYJG".equals(req.getOrder()) && req.getTrendId() == null) {
                throw new BusinessException(ErrorCodeEnum.ECRM0010.getMsg(), ErrorCodeEnum.ECRM0010.getCode());
            }
            return portStatic(req);
        } else {
            throw new BusinessException(ErrorCodeEnum.ECRM0001.getMsg(), ErrorCodeEnum.ECRM0001.getCode());
        }
    }

    /**
     * 质押监管与解除质押监管（静态）--大港
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public PledgeOrderDTO portStatic(StaticPledgeOrReliefPledgeReq req) {
        // 请求信息和返回结果入库保存
        DgPledgeStatic dgPledgeStatic = new DgPledgeStatic();
        dgPledgeStatic.setShipCycleId(req.getShipNo()).setCargoNo(req.getSellNo())
            .setShipCabinQty(new BigDecimal(req.getWatchAmount()).setScale(0, BigDecimal.ROUND_HALF_UP))
            .setShipCabinWeight(new BigDecimal(req.getWatchWeight()).setScale(6, BigDecimal.ROUND_HALF_UP))
            .setOrders(req.getOrder()).setIsPartialRelease(req.getIsPartialRelease())
            .setRelatedTrendId(req.getTrendId());
        BeanUtil.setGenericInfo(dgPledgeStatic, req);
        dgPledgeStaticMapper.insert(dgPledgeStatic);

        Map<String, Object> params = new HashMap<>(7);

        String orderCode = req.getOrder();
        if ("ZYJG".equals(req.getOrder())) {
            orderCode = "1";
        } else if ("JCZYJG".equals(req.getOrder())) {
            orderCode = "2";
        }
        // 机构ID
        params.put("id", PORT_ORANG_ID);
        params.put("shipcycleid", req.getShipNo());
        params.put("cargono", req.getSellNo());
        params.put("pledgenumber", req.getWatchAmount());
        params.put("pledgeweight", req.getWatchWeight());
        params.put("ordercode", orderCode);
        params.put("trendid", dgPledgeStatic.getId() + "J");
        params.put("ispartialrelease", req.getIsPartialRelease());
        if (req.getTrendId() != null) {
            params.put("relatedtrendid", req.getTrendId() + "J");
        }
        JSONObject apiResult = portApiHelper.sendApi(PortUriEnum.STATIC_PLDGE_OR_RELIEF, params, req);

        // JSONObject apiResult =
        // JSONObject.parseObject("{\"success\":true,\"errorMsg\":\"指令发送成功\",\"errorCode\":\"0\"}");
        String result = apiResult.getString("result");
        String message = apiResult.getString("message");
        if (!result.equals(PortApiHelper.STATUS_SUCCESS)) {
            throw new BusinessException(message, result);
        }

        // 返回成功
        PledgeOrderDTO pledgeOrderDTO = new PledgeOrderDTO();
        pledgeOrderDTO.setTrendId(String.valueOf(dgPledgeStatic.getId()));

        return pledgeOrderDTO;
    }

    /**
     * 质押监管与解除质押监管（静态）--冷链
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public PledgeOrderDTO coldChainStatic(StaticPledgeOrReliefPledgeReq req) {
        // 请求信息和返回结果入库保存
        ColdchainPledgeStatic coldchainPledgeStatic = new ColdchainPledgeStatic();
        coldchainPledgeStatic.setDetailId(req.getTaskId()).setPledgeNumber(req.getWatchAmount())
            .setPledgeWeight(req.getWatchWeight()).setOrders(req.getOrder()).setRelatedTrendId(req.getTrendId());

        BeanUtil.setGenericInfo(coldchainPledgeStatic, req);
        coldChainStaticPledgeMapper.insert(coldchainPledgeStatic);
        Map<String, Object> params = new HashMap<>(7);

        // params.put("accountId", COLD_CHAIN_ACCOUNT_ID);
        params.put("accountId", mainBusinessConfig.getColdchainAccount());
        params.put("id", req.getTaskId());
        params.put("pledgeNumber", req.getWatchAmount());
        params.put("pledgeWeight", req.getWatchWeight());
        params.put("order", req.getOrder());
        params.put("trendId", coldchainPledgeStatic.getId());
        params.put("relatedTrendId", req.getTrendId());
        JSONObject apiResult = coldChainApiHelper.sendApi(ColdChainUriEnum.STATIC_PLDGE_OR_RELIEF, params, req);
        // JSONObject apiResult =
        // JSONObject.parseObject("{\"success\":true,\"errorMsg\":\"指令发送成功\",\"errorCode\":\"0\"}");
        Integer code = apiResult.getInteger("errorCode");
        String message = apiResult.getString("errorMsg");

        if (!code.equals(ColdChainApiHelper.STATUS_SUCCESS)) {
            throw new BusinessException(message, String.valueOf(code));
        }

        // 返回成功
        PledgeOrderDTO pledgeOrderDTO = new PledgeOrderDTO();
        pledgeOrderDTO.setTrendId(String.valueOf(coldchainPledgeStatic.getId()));

        return pledgeOrderDTO;
    }

    /**
     * @return com.ynet.core.common.ServiceResult
     * @Description 质押监管与解除质押监管（动态）
     * @Author zhangyongbin
     * @Date 2020/8/18 11:24
     * @Param [req] 请求信息
     **/
    @Transactional(rollbackFor = Exception.class)
    public PledgeOrderDTO dynamicPledgeOrRelief(DynamicPledgeOrReliefPledgeReq req) {
        if (CHANNEL_TYEP_COLDCHAIN.equals(req.getChanType())) {
            /*if (StringUtils.isEmpty(req.getOrganId())) {
                throw new BusinessException(ErrorCodeEnum.ECRM0003.getMsg(), ErrorCodeEnum.ECRM0003.getCode());
            }*/
            return coldChainDynamic(req);
        } else if (CHANNEL_TYEP_PORT.equals(req.getChanType())) {
            if (StringUtils.isEmpty(req.getUserName())) {
                throw new BusinessException(ErrorCodeEnum.ECRM0006.getMsg(), ErrorCodeEnum.ECRM0006.getCode());
            }
            if (StringUtils.isEmpty(req.getTypeName())) {
                throw new BusinessException(ErrorCodeEnum.ECRM0007.getMsg(), ErrorCodeEnum.ECRM0007.getCode());
            }
            if ("JCZYJG".equals(req.getOrder()) && req.getTrendId() == null) {
                throw new BusinessException(ErrorCodeEnum.ECRM0010.getMsg(), ErrorCodeEnum.ECRM0010.getCode());
            }
            return portDynamic(req);
        } else {
            throw new BusinessException(ErrorCodeEnum.ECRM0001.getMsg(), ErrorCodeEnum.ECRM0001.getCode());
        }
    }

    /**
     * 质押监管与解除质押监管（动态）--大港
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public PledgeOrderDTO portDynamic(DynamicPledgeOrReliefPledgeReq req) {
        // 请求信息和返回结果入库保存
        DynamicStaticResult dynamicStaticResult = new DynamicStaticResult();
        dynamicStaticResult.setDetailId(req.getTaskId()).setPledgeNumber(req.getLowAmount())
            .setPledgeWeight(req.getLowWeight()).setOrders(req.getOrder()).setSystemSource(req.getChanType())
            .setWorkentrustId(req.getUserNo()).setWorkentrustName(req.getUserName()).setCargoNameCode(req.getTypeCode())
            .setCargoName(req.getTypeName()).setIsPartialRelease(req.getIsPartialRelease())
            .setRelatedTrendId(req.getTrendId()).setFormatSizeName(req.getFormatSizeName());
        BeanUtil.setGenericInfo(dynamicStaticResult, req);
        coldChainDynamicPledgeMapper.insert(dynamicStaticResult);

        Map<String, Object> params = new HashMap<>(10);
        /**
         * TODO 参数待调整
         */
        String orderCode = req.getOrder();
        if ("ZYJG".equals(req.getOrder())) {
            orderCode = "1";
        } else if ("JCZYJG".equals(req.getOrder())) {
            orderCode = "2";
        }
        params.put("id", PORT_ORANG_ID);
        // params.put("trendId", req.getTaskId());
        params.put("cargonamecode", req.getTypeCode());
        params.put("cargoname", req.getTypeName());
        params.put("workentrustid", req.getUserNo());
        params.put("workentrustname", req.getUserName());
        params.put("formatsizename", req.getFormatSizeName());
        params.put("riskcontrolqty", req.getLowAmount());
        params.put("riskcontrolweight", req.getLowWeight());
        params.put("ordercode", orderCode);
        params.put("trendid", dynamicStaticResult.getId() + "D");
        params.put("ispartialrelease", req.getIsPartialRelease());
        if (req.getTrendId() != null) {
            params.put("relatedtrendid", req.getTrendId() + "D");
        }
        JSONObject apiResult = portApiHelper.sendApi(PortUriEnum.DYNAMIC_PLDGE_OR_RELIEF, params, req);
        // JSONObject apiResult =
        // JSONObject.parseObject("{\"success\":true,\"errorMsg\":\"指令发送成功\",\"errorCode\":\"0\"}");
        String result = apiResult.getString("result");
        String message = apiResult.getString("message");
        if (!result.equals(PortApiHelper.STATUS_SUCCESS)) {
            throw new BusinessException(message, result);
        }

        // 返回成功
        PledgeOrderDTO pledgeOrderDTO = new PledgeOrderDTO();
        pledgeOrderDTO.setTrendId(String.valueOf(dynamicStaticResult.getId()));

        return pledgeOrderDTO;
    }

    /**
     * 质押监管与解除质押监管（动态）--冷链
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public PledgeOrderDTO coldChainDynamic(DynamicPledgeOrReliefPledgeReq req) {

        // 请求信息和返回结果入库保存
        DynamicStaticResult dynamicStaticResult = new DynamicStaticResult();
        dynamicStaticResult.setDetailId(req.getTaskId()).setPledgeNumber(req.getLowAmount())
            .setPledgeWeight(req.getLowWeight()).setOrders(req.getOrder()).setItemClass(req.getTypeCode())
            .setCustomerNumber(req.getUserNo()).setSystemSource(req.getChanType()).setRelatedTrendId(req.getTrendId());
        BeanUtil.setGenericInfo(dynamicStaticResult, req);
        coldChainDynamicPledgeMapper.insert(dynamicStaticResult);

        Map<String, Object> params = new HashMap<>(7);

        // params.put("accountId", COLD_CHAIN_ACCOUNT_ID);
        params.put("accountId", mainBusinessConfig.getColdchainAccount());
        params.put("id", req.getTaskId());
        params.put("pledgeNumber", req.getLowAmount());
        params.put("pledgeWeight", req.getLowWeight());
        params.put("order", req.getOrder());
        params.put("itemClass", req.getTypeName());
        params.put("customerNumber", req.getUserNo());
        params.put("trendId", dynamicStaticResult.getId());
        params.put("relatedTrendId", req.getTrendId());

        JSONObject apiResult = coldChainApiHelper.sendApi(ColdChainUriEnum.DYNAMIC_PLDGE_OR_RELIEF, params, req);
        // JSONObject apiResult =
        // JSONObject.parseObject("{\"success\":true,\"errorMsg\":\"指令发送成功\",\"errorCode\":\"0\"}");
        Integer code = apiResult.getInteger("errorCode");
        String message = apiResult.getString("errorMsg");

        if (!code.equals(ColdChainApiHelper.STATUS_SUCCESS)) {
            throw new BusinessException(message, String.valueOf(code));
        }

        // 返回成功
        PledgeOrderDTO pledgeOrderDTO = new PledgeOrderDTO();
        pledgeOrderDTO.setTrendId(String.valueOf(dynamicStaticResult.getId()));

        return pledgeOrderDTO;
    }

    /**
     * @return com.ynet.core.common.ServiceResult
     * @Description 换货指令
     * @Author zhangyongbin
     * @Date 2020/8/18 11:24
     * @Param [req] 请求信息
     **/
    @Transactional(rollbackFor = Exception.class)
    public PledgeOrderDTO changeGoodsOrder(ChangeGoodsOrderReq req) {
        if (CHANNEL_TYEP_COLDCHAIN.equals(req.getChanType())) {
            if (StringUtils.isEmpty(req.getTaskId())) {
                throw new BusinessException(ErrorCodeEnum.ECRM0002.getMsg(), ErrorCodeEnum.ECRM0002.getCode());
            }
            return coldChainChangeOrder(req);
        } else if (CHANNEL_TYEP_PORT.equals(req.getChanType())) {
            if (StringUtils.isEmpty(req.getOldShipNo())) {
                throw new BusinessException(ErrorCodeEnum.ECRM0004.getMsg(), ErrorCodeEnum.ECRM0004.getCode());
            }
            if (StringUtils.isEmpty(req.getOldSellNo())) {
                throw new BusinessException(ErrorCodeEnum.ECRM0005.getMsg(), ErrorCodeEnum.ECRM0005.getCode());
            }
            if (StringUtils.isEmpty(req.getShipNo())) {
                throw new BusinessException(ErrorCodeEnum.ECRM0008.getMsg(), ErrorCodeEnum.ECRM0008.getCode());
            }
            if (StringUtils.isEmpty(req.getSellNo())) {
                throw new BusinessException(ErrorCodeEnum.ECRM0009.getMsg(), ErrorCodeEnum.ECRM0009.getCode());
            }
            return portChangeOrder(req);
        } else {
            throw new BusinessException(ErrorCodeEnum.ECRM0001.getMsg(), ErrorCodeEnum.ECRM0001.getCode());
        }
    }

    /**
     * 换货指令--大港
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public PledgeOrderDTO portChangeOrder(ChangeGoodsOrderReq req) {
        // 请求信息和返回结果入库保存
        /**
         * 原质押解除信息
         */
        DgPledgeStatic oldPledge = new DgPledgeStatic();
        oldPledge.setShipCycleId(req.getOldShipNo()).setCargoNo(req.getOldSellNo())
            .setIsPartialRelease(req.getIsPartialRelease()).setRelatedId(req.getTrendId());
        if (StringUtils.isNotBlank(req.getOldWatchAmount())) {
            oldPledge.setShipCabinQty(new BigDecimal(req.getOldWatchAmount()).setScale(0, BigDecimal.ROUND_HALF_UP));
        }
        if (StringUtils.isNotBlank(req.getOldWatchWeight())) {
            oldPledge.setShipCabinWeight(new BigDecimal(req.getOldWatchWeight()).setScale(6, BigDecimal.ROUND_HALF_UP));
        }
        oldPledge.setOrders(req.getOldOrder());
        BeanUtil.setGenericInfo(oldPledge, req);
        dgPledgeStaticMapper.insert(oldPledge);

        /**
         * 新质押信息
         */
        DgPledgeStatic newPledge = new DgPledgeStatic();
        newPledge.setShipCycleId(req.getShipNo()).setCargoNo(req.getSellNo())
            .setIsPartialRelease(req.getIsPartialRelease()).setRelatedId(req.getTrendId());
        if (StringUtils.isNotBlank(req.getWatchAmount())) {
            newPledge.setShipCabinQty(new BigDecimal(req.getWatchAmount()).setScale(0, BigDecimal.ROUND_HALF_UP));
        }
        if (StringUtils.isNotBlank(req.getWatchWeight())) {
            newPledge.setShipCabinWeight(new BigDecimal(req.getWatchWeight()).setScale(6, BigDecimal.ROUND_HALF_UP));
        }
        newPledge.setOrders(req.getOrder());
        BeanUtil.setGenericInfo(newPledge, req);
        dgPledgeStaticMapper.insert(newPledge);

        Map<String, Object> params = new HashMap<>(16);
        /**
         * TODO 参数待调整
         */
        params.put("id", PORT_ORANG_ID);
        params.put("trendid", newPledge.getId() + "J");// 主键
        params.put("shipcycleid", req.getShipNo());
        params.put("cargono", req.getSellNo());
        params.put("pledgenumber", req.getWatchAmount());
        params.put("pledgeweight", req.getWatchWeight());
        params.put("ordercode", "3");
        // params.put("pledgeid", req.getOldtaskId());// 原押品主键
        params.put("sourceshipcycleid", req.getOldShipNo());
        params.put("sourcecargono", req.getOldSellNo());
        params.put("relievenumber", req.getOldWatchAmount());
        params.put("relieveweight", req.getOldWatchWeight());
        // params.put("relieveOrder", req.getOldOrder());
        params.put("ispartialrelease", req.getIsPartialRelease());
        params.put("pledgeid", oldPledge.getId() + "J");
        params.put("relatedtrendid", req.getTrendId() + "J");

        JSONObject apiResult = portApiHelper.sendApi(PortUriEnum.CHANGE_GOODS_ORDER, params, req);
        // JSONObject apiResult =
        // JSONObject.parseObject("{\"success\":true,\"errorMsg\":\"指令发送成功\",\"errorCode\":\"0\"}");
        String code = apiResult.getString("result");
        String message = apiResult.getString("message");

        if (!code.equals(PortApiHelper.STATUS_SUCCESS)) {
            throw new BusinessException(message, String.valueOf(code));
        }

        // 返回成功
        PledgeOrderDTO pledgeOrderDTO = new PledgeOrderDTO();
        pledgeOrderDTO.setTrendId(String.valueOf(newPledge.getId()));
        pledgeOrderDTO.setRelieveTrendId(String.valueOf(oldPledge.getId()));

        return pledgeOrderDTO;

    }

    /**
     * 换货指令--冷链
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public PledgeOrderDTO coldChainChangeOrder(ChangeGoodsOrderReq req) {
        // 请求信息和返回结果入库保存
        /**
         * 原质押解除信息
         */
        ColdchainPledgeStatic oldPledge = new ColdchainPledgeStatic();
        oldPledge.setDetailId(req.getOldtaskId()).setPledgeNumber(req.getOldWatchAmount())
            .setPledgeWeight(req.getOldWatchWeight()).setOrders(req.getOldOrder());
        BeanUtil.setGenericInfo(oldPledge, req).setRelatedTrendId(req.getTrendId());
        coldChainStaticPledgeMapper.insert(oldPledge);

        /**
         * 新质押信息
         */
        ColdchainPledgeStatic newPledge = new ColdchainPledgeStatic();
        newPledge.setDetailId(req.getTaskId()).setPledgeNumber(req.getWatchAmount())
            .setPledgeWeight(req.getWatchWeight()).setOrders(req.getOrder()).setRelatedTrendId(req.getTrendId());

        BeanUtil.setGenericInfo(newPledge, req);
        coldChainStaticPledgeMapper.insert(newPledge);

        Map<String, Object> params = new HashMap<>(12);

        // params.put("accountId", COLD_CHAIN_ACCOUNT_ID);
        params.put("accountId", mainBusinessConfig.getColdchainAccount());
        params.put("id", req.getTaskId());
        params.put("pledgeNumber", req.getOldWatchAmount());
        params.put("pledgeWeight", req.getOldWatchWeight());
        params.put("order", req.getOrder());
        params.put("pledgeId", req.getOldtaskId());
        params.put("relieveNumber", req.getOldWatchAmount());
        params.put("relieveWeight", req.getOldWatchWeight());
        params.put("relieveOrder", req.getOldOrder());
        params.put("sourceTrendId", oldPledge.getId());
        params.put("relatedTrendId", req.getTrendId());
        params.put("trendId", newPledge.getId());

        JSONObject apiResult = coldChainApiHelper.sendApi(ColdChainUriEnum.CHANGE_GOODS_ORDER, params, req);
        // JSONObject apiResult =
        // JSONObject.parseObject("{\"success\":true,\"errorMsg\":\"指令发送成功\",\"errorCode\":\"0\"}");
        Integer code = apiResult.getInteger("errorCode");
        String message = apiResult.getString("errorMsg");

        if (!code.equals(ColdChainApiHelper.STATUS_SUCCESS)) {
            throw new BusinessException(message, String.valueOf(code));
        }

        // 返回成功
        PledgeOrderDTO pledgeOrderDTO = new PledgeOrderDTO();
        pledgeOrderDTO.setTrendId(String.valueOf(newPledge.getId()));
        pledgeOrderDTO.setRelieveTrendId(String.valueOf(oldPledge.getId()));

        return pledgeOrderDTO;
    }

    /**
     * 静态质押/解除结果同步
     *
     * <pre>
     *分两部分：冷链系统、大港系统 主要同步分：静态质押监管/解除 结果同步;
     *动态质押监管/解除 结果同步;
     *换货指令结果同步
     * </pre>
     *
     * @param req 静态质押监管及解除结果同步信息
     * @author liulx
     */
    public String syncPledgeStatic(SyncPledgeStaticReq req) {
        Map<String, Object> mqData = new HashMap<>();
        // 判断数据为是冷链，还是大港
        if (CHANNEL_TYEP_COLDCHAIN.equals(req.getChanType())) {
            // 冷链处理
            /* SyncPledgeStaticColdChainReq yzhData = req.getYzhData();
            if (yzhData == null) {
               throw new BusinessException("冷链静态质押监管及解除结果同步信息不能为空", "ECRM0001");
            }*/
            updateColdchainStaticToDb(req);
            mqData.put("systemFlag", req.getChanType());
            mqData.put("accountId", req.getUserNo());
            mqData.put("name", req.getUserName());
            mqData.put("id", req.getTrendId());
            mqData.put("pledgeNumber", req.getWatchAmount());
            mqData.put("pledgeWeight", req.getWatchWeight());
            mqData.put("order", req.getOrder());
            mqData.put("result", req.getResult());
            mqData.put("reason", req.getReason());
        } else if (CHANNEL_TYEP_PORT.equals(req.getChanType())) {
            // 大港处理
            /*SyncPledgeStaticDgReq dgData = req.getDgData();
            if (dgData == null) {
                throw new BusinessException("大港静态质押监管及解除结果同步信息不能为空", "ECRM0001");
            }*/
            updateDgStaticToDb(req);
            Map map = mapper.map(req, Map.class);
            mqData = (Map<String, Object>)map;
            mqData.put("systemFlag", req.getChanType());
        } else {
            throw new BusinessException("系统标志值错误", "ECCT0400");
        }
        // 将结果信息通过 MQ 推送至渠道
        pledgeProducer.sendMessagesStaticResult(mqData);
        String returnsResult = SystemConstant.SYSTEM_SUCCESS;
        return returnsResult;
    }

    /**
     * 同步冷链静态质押（或解除）结果至数据库
     *
     * @param reqObj 冷链静态质押监管及解除结果同步信息
     * @author liulx
     */
    @Transactional(rollbackFor = Exception.class)
    protected void updateColdchainStaticToDb(SyncPledgeStaticReq reqObj) {
        LambdaQueryWrapper<ColdchainPledgeStatic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ColdchainPledgeStatic::getId, reqObj.getTrendId());
        ColdchainPledgeStatic obj = coldChainStaticPledgeMapper.selectOne(queryWrapper);
        if (obj == null) {
            throw new BusinessException("数据不存在", "ECRM0004");
        }
        // SyncPledgeStaticColdChainReq req = reqObj.getYzhData();
        obj.setAccountId(reqObj.getUserNo());
        obj.setName(reqObj.getUserName());
        obj.setDetailId(reqObj.getTrendId());
        obj.setPledgeNumber(reqObj.getWatchAmount());
        obj.setPledgeWeight(reqObj.getWatchWeight());
        obj.setOrders(reqObj.getOrder());
        obj.setResult(reqObj.getResult());
        obj.setReason(reqObj.getReason());
        coldChainStaticPledgeMapper.updateById(obj);
    }

    /**
     * 同步大港静态质押（或解除）结果至数据库
     *
     * @param reqObj 大港静态质押监管及解除结果同步信息
     * @author liulx
     */
    @Transactional(rollbackFor = Exception.class)
    protected void updateDgStaticToDb(SyncPledgeStaticReq reqObj) {
        LambdaQueryWrapper<DgPledgeStatic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DgPledgeStatic::getId, reqObj.getTrendId());
        DgPledgeStatic obj = dgPledgeStaticMapper.selectOne(queryWrapper);
        if (obj == null) {
            throw new BusinessException("数据不存在", "ECRM0004");
        }
        // SyncPledgeStaticDgReq req = reqObj.getDgData();
        obj.setOrders(reqObj.getOrder());
        obj.setResult(reqObj.getResult());
        obj.setReson(reqObj.getReason());
        obj.setGmtModified(LocalDateTime.now());
        dgPledgeStaticMapper.updateById(obj);
    }

    /**
     * 动态质押/解除结果同步
     *
     * <pre>
     *分两部分：冷链系统、大港系统 主要同步分：动态质押监管/解除 结果同步;
     *动态质押监管/解除 结果同步，换货指令结果同步
     * </pre>
     *
     * @param req 动态质押监管及解除结果同步信息
     * @author liulx
     */
    @Transactional(rollbackFor = Exception.class)
    public String syncPledgeDynamic(SyncPledgeDynamicReq req) {
        Map<String, Object> data = null;
        // 判断数据为是冷链，还是大港
        if (CHANNEL_TYEP_COLDCHAIN.equals(req.getChanType())) {
            // 冷链处理
            updateColdchainDynamicToDb(req);
            data = getDynamicResultMessage(req);
        } else if (CHANNEL_TYEP_PORT.equals(req.getChanType())) {
            // 大港处理
            updatePortDynamicToDb(req);
            data = getDynamicResultMessage(req);
            LambdaQueryWrapper<DynamicStaticResult> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DynamicStaticResult::getId, req.getTrendId());
            DynamicStaticResult dgObj = coldChainDynamicPledgeMapper.selectOne(queryWrapper);
            if (dgObj == null) {
                throw new BusinessException("数据不存在", "ECRM0004");
            }
            // 补充大港的字段
            data.put("workentrustId", dgObj.getWorkentrustId());
            data.put("workentrustName", dgObj.getWorkentrustName());
            data.put("cargonameCode", dgObj.getCargoNameCode());
            data.put("cargoName", dgObj.getCargoName());
            data.put("formatsizeName", dgObj.getFormatSizeName());
        } else {
            throw new BusinessException("系统标志值错误", "ECCT0400");
        }
        // 将结果信息通过 MQ 推送至渠道
        pledgeProducer.sendMessagesDynamicResult(data);
        String returnsResult = SystemConstant.SYSTEM_SUCCESS;
        return returnsResult;
    }

    /**
     * 将冷链处理的动态质押指令结果转换成 Map，用于推送至消息队列
     * 
     * @param req
     * @return
     * @author liulx
     */
    private Map<String, Object> getDynamicResultMessage(SyncPledgeDynamicReq req) {
        Map<String, Object> data = new HashMap<>(16);
        data.put("traceId", req.getTraceId());
        data.put("requestTime", req.getRequestTime());
        data.put("channel", req.getChannel());
        data.put("systemFlag", req.getChanType());
        data.put("trendId", req.getTrendId());
        data.put("id", req.getTrendId());
        data.put("pledgeNumber", req.getLowAmount());
        data.put("pledgeWeight", req.getLowWeight());
        data.put("order", req.getOrder());
        data.put("result", req.getResult());
        data.put("reason", req.getReason());
        return data;
    }

    /**
     * 同步冷链动态质押（或解除）结果至数据库
     *
     * @param req 冷链动态质押监管及解除结果同步信息
     * @author liulx
     */
    @Transactional(rollbackFor = Exception.class)
    protected void updateColdchainDynamicToDb(SyncPledgeDynamicReq req) {
        LambdaQueryWrapper<DynamicStaticResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DynamicStaticResult::getId, req.getTrendId());
        DynamicStaticResult obj = coldChainDynamicPledgeMapper.selectOne(queryWrapper);
        if (obj == null) {
            throw new BusinessException("数据不存在", "ECRM0004");
        }
        obj.setPledgeNumber(req.getLowAmount());
        obj.setPledgeWeight(req.getLowWeight());
        obj.setOrders(req.getOrder());
        obj.setResult(req.getResult());
        obj.setReason(req.getReason());
        coldChainDynamicPledgeMapper.updateById(obj);
    }

    /**
     * 同步大港动态质押（或解除）结果至数据库
     *
     * @param req 大港动态质押监管及解除结果同步信息
     * @author liulx
     */
    @Transactional(rollbackFor = Exception.class)
    protected void updatePortDynamicToDb(SyncPledgeDynamicReq req) {
        LambdaQueryWrapper<DynamicStaticResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DynamicStaticResult::getId, req.getTrendId());
        DynamicStaticResult obj = coldChainDynamicPledgeMapper.selectOne(queryWrapper);
        if (obj == null) {
            throw new BusinessException("数据不存在", "ECRM0004");
        }
        obj.setPledgeNumber(req.getLowAmount());
        obj.setPledgeWeight(req.getLowWeight());
        obj.setOrders(req.getOrder());
        obj.setResult(req.getResult());
        obj.setReason(req.getReason());
        coldChainDynamicPledgeMapper.updateById(obj);
    }

    /**
     * 同步换货指令结果
     * 
     * @param req
     * @author liulx
     */
    public String syncExchange(SyncExchangeReq req) {
        Map<String, Object> mqData;
        // 判断数据为是冷链，还是大港
        if (CHANNEL_TYEP_COLDCHAIN.equals(req.getChanType())) {
            // 冷链处理
            /*  if (StringUtils.isEmpty(req.getTaskId())) {
              throw new BusinessException("在库明细主键不能为空", "ECRM0001");
            }
            if (StringUtils.isEmpty(req.getOldTaskId())) {
              throw new BusinessException("原在库明细主键不能为空", "ECRM0001");
            }*/
            updateColdchainExchangeToDb(req);
            mqData = getExchangeColdchainMessage(req);
        } else if (CHANNEL_TYEP_PORT.equals(req.getChanType())) {
            // 大港处理
            updateDgExchangeToDb(req);
            mqData = getExchangePortMessage(req);
        } else {
            throw new BusinessException("系统标志值错误", "ECCT0400");
        }
        // 将结果信息通过 MQ 推送至渠道
        pledgeProducer.sendMessagesExchange(mqData);
        String returnsResult = SystemConstant.SYSTEM_SUCCESS;
        return returnsResult;
    }

    /**
     * 将冷链处理的换货指令结果转换成 Map，用于推送至消息队列
     * 
     * @param req
     * @return
     * @author liulx
     */
    private Map<String, Object> getExchangeColdchainMessage(SyncExchangeReq req) {
        LambdaQueryWrapper<ColdchainPledgeStatic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ColdchainPledgeStatic::getId, req.getTrendId());
        ColdchainPledgeStatic obj = coldChainStaticPledgeMapper.selectOne(queryWrapper);

        Map<String, Object> data = new HashMap<>(16);
        data.put("traceId", req.getTraceId());
        data.put("requestTime", req.getRequestTime());
        data.put("channel", req.getChannel());
        data.put("systemFlag", req.getChanType());
        Map<String, Object> yzhData = new HashMap<>(16);
        // data.put("accountId", COLD_CHAIN_ACCOUNT_ID);
        data.put("accountId", mainBusinessConfig.getColdchainAccount());
        // trendId 中台落库后的唯一标识
        yzhData.put("trendId", req.getTrendId());
        yzhData.put("id", req.getTrendId());
        yzhData.put("pledgeNumber", obj.getPledgeNumber());
        yzhData.put("pledgeWeight", obj.getPledgeWeight());
        yzhData.put("order", req.getOrder());
        yzhData.put("pledgeId", req.getSourceTrendId());
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ColdchainPledgeStatic::getId, req.getSourceTrendId());
        ColdchainPledgeStatic oldObj = coldChainStaticPledgeMapper.selectOne(queryWrapper);

        yzhData.put("relieveNumber", oldObj.getPledgeNumber());
        yzhData.put("relieveWeight", oldObj.getPledgeWeight());
        yzhData.put("relieveOrder", req.getOrder());
        yzhData.put("result", req.getResult());
        yzhData.put("reason", req.getReason());
        data.put("yzhData", yzhData);
        return data;
    }

    /**
     * 将大港处理的换货指令结果转换成 Map，用于推送至消息队列
     * 
     * @param req
     * @return
     * @author liulx
     */
    private Map<String, Object> getExchangePortMessage(SyncExchangeReq req) {
        LambdaQueryWrapper<DgPledgeStatic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DgPledgeStatic::getId, req.getTrendId());
        DgPledgeStatic obj = dgPledgeStaticMapper.selectOne(queryWrapper);

        Map<String, Object> data = new HashMap<>(32);
        data.put("traceId", req.getTraceId());
        data.put("requestTime", req.getRequestTime());
        data.put("channel", req.getChannel());
        data.put("systemFlag", req.getChanType());
        Map<String, Object> dgData = new HashMap<>(16);
        // trendId 中台落库后的唯一标识
        dgData.put("trendId", req.getTrendId());
        dgData.put("shipcycleId", obj.getShipCycleId());
        dgData.put("cargoNo", obj.getCargoNameCode());
        dgData.put("pledgeNumber", obj.getShipCabinQty());
        dgData.put("pledgeWeight", obj.getShipCabinWeight());
        dgData.put("order", req.getOrder());
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DgPledgeStatic::getId, req.getTrendId());
        DgPledgeStatic oldObj = dgPledgeStaticMapper.selectOne(queryWrapper);

        dgData.put("oldShipcycleId", oldObj.getShipCycleId());
        dgData.put("oldCargoNo", oldObj.getCargoNo());
        dgData.put("relieveWeight", oldObj.getShipCabinQty());
        dgData.put("relieveNumber", oldObj.getShipCabinWeight());
        dgData.put("relieveOrder", req.getOrder());
        dgData.put("result", req.getResult());
        dgData.put("reason", req.getReason());
        data.put("dgData", dgData);
        return data;
    }

    /**
     * 更新冷链换货信息
     * 
     * <pre>
     *     换货更新两条数据，一条为新质押的数据状态
     *     一条为解质押的数据状态
     * </pre>
     * 
     * @param req 换货指令结果同步请求信息
     * @author liulx
     */
    @Transactional(rollbackFor = Exception.class)
    protected void updateColdchainExchangeToDb(SyncExchangeReq req) {
        // 更新新质押的数据状态
        LambdaQueryWrapper<ColdchainPledgeStatic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ColdchainPledgeStatic::getId, req.getTrendId());
        ColdchainPledgeStatic obj = coldChainStaticPledgeMapper.selectOne(queryWrapper);
        if (obj == null) {
            throw new BusinessException("数据不存在", "ECRM0004");
        }
        obj.setIsExchange(true);
        obj.setRelatedId(Integer.valueOf(req.getSourceTrendId()));
        // obj.setDetailId(req.getTrendId());
        obj.setOrders(req.getOrder());
        obj.setResult(req.getResult());
        obj.setReason(req.getReason());
        coldChainStaticPledgeMapper.updateById(obj);

        // 更新解除质押的数据状态
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ColdchainPledgeStatic::getId, req.getSourceTrendId());
        ColdchainPledgeStatic oldObj = coldChainStaticPledgeMapper.selectOne(queryWrapper);
        if (oldObj == null) {
            throw new BusinessException("数据不存在", "ECRM0004");
        }
        oldObj.setIsExchange(true);
        oldObj.setRelatedId(Integer.valueOf(req.getTrendId()));
        oldObj.setDetailId(req.getSourceTrendId());
        oldObj.setOrders(req.getOrder());
        oldObj.setResult(req.getResult());
        oldObj.setReason(req.getReason());
        coldChainStaticPledgeMapper.updateById(oldObj);
    }

    /**
     * 更新大港换货信息
     *
     * <pre>
     *     换货更新两条数据，一条为新质押的数据状态
     *     一条为解质押的数据状态
     * </pre>
     *
     * @param req 换货指令结果同步请求信息
     * @author liulx
     */
    @Transactional(rollbackFor = Exception.class)
    protected void updateDgExchangeToDb(SyncExchangeReq req) {
        // 更新新质押的数据状态
        LambdaQueryWrapper<DgPledgeStatic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DgPledgeStatic::getId, req.getTrendId());
        DgPledgeStatic obj = dgPledgeStaticMapper.selectOne(queryWrapper);
        if (obj == null) {
            throw new BusinessException("数据不存在", "ECRM0004");
        }
        obj.setIsExchange(true);
        obj.setRelatedId(Integer.valueOf(req.getSourceTrendId()));
        obj.setOrders(req.getOrder());
        obj.setResult(req.getResult());
        obj.setReson(req.getReason());
        dgPledgeStaticMapper.updateById(obj);

        // 更新解除质押的数据状态
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DgPledgeStatic::getId, req.getSourceTrendId());
        DgPledgeStatic oldObj = dgPledgeStaticMapper.selectOne(queryWrapper);
        if (oldObj == null) {
            throw new BusinessException("数据不存在", "ECRM0004");
        }
        oldObj.setIsExchange(true);
        oldObj.setRelatedId(Integer.valueOf(req.getTrendId()));
        oldObj.setOrders(req.getOrder());
        oldObj.setResult(req.getResult());
        oldObj.setReson(req.getReason());
        dgPledgeStaticMapper.updateById(oldObj);
    }

}
